require 'fileaction'

class FileManagerException < Exception
end

class FileManager
  def self.can_execute?(afile, amenu)
    action = amenu.url 
    ((afile != nil) and 
      ((afile.isimage? and is_image?(action)) or 
       (afile.iszip? and action == 'unzip') or
       (afile.israr? and action == 'unrar') or 
       ((action == 'zip') and not afile.iszip?) or 
       (action == 'copy') or 
       ((action == 'rar') and not afile.israr?) or
       (afile.is_writer? and amenu.is_for_writer?) or
       (afile.is_calc? and amenu.is_for_calc?) or
       (afile.is_presentation? and amenu.is_for_presentation?)
      ) 
     ) or 
     (action == '#') or
     (action == 'upload')
  end
  
  private
    def self.is_image?(action)
         (action == "jpg") or 
         (action == "bmp") or 
         (action == "png") or 
         (action == "tiff") or 
         (action == "ico") or 
         (action == "pdf") or          
         (action == "gif") 
    end

    def self.find_class(afile)
      if afile.iszip?
        return ZipArchive
      elsif afile.israr?
        return RarArchive
      else
        raise "find_class: unknown file"
      end
    end
    
  public
    def self.execute(afile, amenu)
      action = amenu.url
      lclass = nil
      larchive_class = nil
      
      #todo: should call can_execute? here just for security

      #search for convertion class
      if (amenu.is_for_writer? and afile.is_writer?) or 
        (amenu.is_for_calc? and afile.is_calc?) or 
        (amenu.is_for_presentation? and afile.is_presentation?)
        laction = OOConvert.new(afile, amenu.description, amenu.ext)
      elsif is_image?(action) 
        laction = ConvertImage.new(afile, action)
      else    
        case action
          when "zip"
            lclass = ZipArchive
          when "rar"
            lclass = RarArchive
          when "copy"
            lclass = CopyFile
          when "unzip"
            lclass = UnzipArchive
          when "unrar"
            lclass = UnrarArchive
          else
            raise FileManagerException, "unknown action: " + action 
        end
        
        laction = lclass.new(afile);
      end    

      if laction.is_a?(AbstractArchive) and afile.isarchive?
        larchive_class=find_class(afile)
        larchive_action = larchive_class.new(afile)
        laction.execute_archive(larchive_action)
      else      
        #execute action
        laction.execute()
      end

    end  
end
